const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    planId: '',
    processId: '',
    process: null,
    plan: null,
    userList: [],
    selectedUserId: null,
    quantity: '',
    loading: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/allocate-process/allocate-process')) {
      return
    }
    
    if (options.planId && options.processId) {
      this.setData({
        planId: options.planId,
        processId: options.processId
      })
      this.loadData()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载数据
  loadData() {
    this.setData({ loading: true })
    
    // 加载分配数据
    app.request({
      url: '/allocateProductionPlan',
      method: 'GET',
      data: { plan_id: this.data.planId }
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        const data = res.data
        
        // 将userList对象转换为数组格式
        const userListArray = data.userList ? Object.keys(data.userList).map(id => ({
          id: parseInt(id),
          username: data.userList[id],
          nickname: data.userList[id]
        })) : []
        
        // 找到当前工序
        const process = data.processListWithAllocation[this.data.processId]
        
        this.setData({
          plan: data.plan,
          process: process,
          userList: userListArray
        })
        
        wx.setNavigationBarTitle({
          title: `分配工序 - ${process.name}`
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载数据失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 选择用户
  selectUser(e) {
    const userId = e.currentTarget.dataset.userId
    this.setData({
      selectedUserId: userId
    })
  },

  // 输入数量
  onQuantityInput(e) {
    this.setData({
      quantity: e.detail.value
    })
  },

  // 提交分配
  submitAllocation() {
    if (!this.data.selectedUserId) {
      wx.showToast({
        title: '请选择用户',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.quantity || this.data.quantity <= 0) {
      wx.showToast({
        title: '请输入有效的分配数量',
        icon: 'none'
      })
      return
    }
    
    const quantity = parseInt(this.data.quantity)
    if (quantity > this.data.process.remaining_quantity) {
      wx.showToast({
        title: `分配数量不能超过剩余数量${this.data.process.remaining_quantity}`,
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '分配中...' })
    
    const allocationData = {
      order_id: this.data.plan.order_id,
      model_id: this.data.plan.model_id,
      process_id: this.data.processId,
      user_id: this.data.selectedUserId,
      quantity: quantity,
      work_type: 'piece', // 默认计件
      plan_id: this.data.planId // 添加plan_id字段
    }
    
    console.log('分配数据:', allocationData)
    console.log('计划信息:', this.data.plan)
    
    app.request({
      url: '/createAllocation',
      method: 'POST',
      data: allocationData
    }).then(res => {
      wx.hideLoading()
      if (res.code === 1) {
        wx.showToast({
          title: '分配成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '分配失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('分配失败:', err)
      wx.showToast({
        title: '分配失败',
        icon: 'none'
      })
    })
  }
})
